package Communication;

import java.io.FileInputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Properties;

public class ClientReceiver extends UnicastRemoteObject implements IClientReceiver {
    private static ClientReceiver instance;
    private int puertoCliente;
    private Registry registro;

    public static ClientReceiver getInstance ( ) {
		if ( instance == null )
			try {
				instance = new ClientReceiver ( );
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return instance;
	}
    
    private ClientReceiver ( ) throws RemoteException {
    	Properties properties = new Properties ( );
    	try {
    		properties.load ( new FileInputStream ( "conexion.properties" ) );
    	    puertoCliente = Integer.parseInt ( properties.getProperty ( "clientPort" ) );
    	} catch (IOException e) {
    		System.out.println ( "File not found" );
    	}
    	//abrirConexion ( );
    }

    public static void abrirConexion ( ) {
    	getInstance ( );
        try {
            instance.registro = LocateRegistry.createRegistry ( instance.puertoCliente );
            instance.registro.rebind ( "rmiChat", instance );
        } catch ( RemoteException e ) {
            e.printStackTrace ( );
        }
    }

	public void recibirMensaje ( Message mensaje ) throws RemoteException {
		Buffer.getInstance ( ).addMessage ( mensaje );
    }
}
